package nought.com.relaceelementinhtmldemo;

import static android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW;

import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;


import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.VideoView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintSet;
import androidx.fragment.app.Fragment;

import com.jeffmony.videocache.VideoProxyCacheManager;
import com.jeffmony.videocache.utils.StorageUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private ConstraintLayout rootView;
    private ScrollWebView webView;
//    private ImageView imageView;
//    private VideoView videoView;
    private String TAG = "MainActivity";
    private ArrayList<VideoViewPager> videoViewPagers = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rootView = (ConstraintLayout) findViewById(R.id.root_view);

        File saveFile = StorageUtils.getVideoFileDir(this);
        if (!saveFile.exists()) {
            saveFile.mkdir();
        }
        Log.d(TAG," TAG " + saveFile.getAbsolutePath());
        VideoProxyCacheManager.Builder builder = new VideoProxyCacheManager.Builder().
                setFilePath(saveFile.getAbsolutePath()).    //缓存存储位置
                        setConnTimeOut(90 * 1000).                  //网络连接超时
                        setReadTimeOut(90 * 1000).                  //网络读超时
                        setExpireTime(365 * 24 * 60 * 60 * 1000).     //2天的过期时间
                        setMaxCacheSize(10 * 1024 * 1024 * 1024);    //2G的存储上限
        VideoProxyCacheManager.getInstance().initProxyConfig(builder.build());

        initView();
        initWebView();


    }

    private void initWebView() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setUseWideViewPort(true);
//        webSettings?.minimumFontSize = 6
//        var videoPath = MyApp.getInstance().filesDir.absolutePath + "/app"
//        webSettings?.setAppCachePath(videoPath)

        webSettings.setCacheMode(WebSettings.LOAD_NORMAL);
//        webSettings?.setAppCacheMaxSize(Long.MAX_VALUE)
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

        webSettings.setDefaultTextEncodingName("utf-8");
        webSettings.setDomStorageEnabled(true);
        webSettings.setBuiltInZoomControls(true);
        //增加JSBridge
        webSettings.setSupportZoom(true);
//        webSettings.setBlockNetworkLoads(false);  //解决图片不显示
        // 设置支持HTTP和HTTPS
        webSettings.setSupportMultipleWindows(true);
        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setAllowFileAccessFromFileURLs(true);

        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        webSettings.setMediaPlaybackRequiresUserGesture(false);  //开启视频自动播放
        webSettings.setMixedContentMode(MIXED_CONTENT_ALWAYS_ALLOW);
        webSettings.setAllowFileAccess(true);
        webSettings.setDisplayZoomControls(false);
        webView.setHorizontalScrollbarOverlay(false) ; //水平不显示
        webView.setVerticalScrollbarOverlay(true);; //垂直不显示
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url) {
                Log.d("hhe", "onPageFinished");
                super.onPageFinished(view, url);
                view.loadUrl("javascript:jsFun.measureImagePlaceHolder();");
            }
        });

        webView.addJavascriptInterface(new JavaFun(), "JavaFun");
        webView.loadUrl("file:///android_asset/test.html");

//        webView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
//            @Override
//            public void onScrollChange(View view, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
//
//            }
//        });

        webView.setOnScrollChangeListener(new ScrollWebView.OnScrollChangeListener() {
            @Override
            public void onPageEnd(int l, int t, int oldl, int oldt) {
                int distanceScrolled = oldl - oldt;
//                params = imageView.getLayoutParams();
                Log.d(TAG,"webView onPageEnd" + distanceScrolled);
                params.topMargin =  setTop + distanceScrolled;
                refreshViewPager(params);
//                videoView.setLayoutParams(params);
            }

            @Override
            public void onPageTop(int l, int t, int oldl, int oldt) {
                int distanceScrolled = oldl - oldt;
                Log.d(TAG,"webView onPageTop    " + distanceScrolled);
                params.topMargin =  setTop ;
                refreshViewPager(params);
//                videoView.setLayoutParams(params);
            }

            @Override
            public void onScrollChanged(int l, int t, int oldl, int oldt) {
                int distanceScrolled = oldl - oldt;
//                setTop = setTop + distanceScrolled;
//                int distanceScrolled = scrollY - oldScrollY;
//                oldt = oldl;

                if (oldl == oldt) { // 滑动停止
                    // 滑动停止时的操作
                }else {

                }
                params.topMargin =  setTop + distanceScrolled;
                refreshViewPager(params);
//                videoView.setLayoutParams(params);
                Log.d(TAG,"webView onScrollChanged" +  params.topMargin);
            }
        });
    }


    private void refreshViewPager(ConstraintLayout.LayoutParams params){
        for(VideoViewPager viewPager:videoViewPagers){
            viewPager.setLayoutParams(params);
        }
    }

    private void initView() {
//        imageView = new ImageView(this);
        webView = findViewById(R.id.webView);
//        webView = new WebView(this);
//        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
//        rootView.addView(webView, layoutParams);
    }

    ConstraintLayout.LayoutParams params;
    private int setTop = 0;

    class JavaFun {

        @JavascriptInterface
        public void replaceImgWithImageView(int left, int top, int width, int height) {
            final Context context = MainActivity.this.getApplicationContext();
//            videoView = (VideoView) findViewById(R.id.videoView);
            params= new ConstraintLayout.LayoutParams(dp2px(context, width* 1.0f), dp2px(context, height* 1.0f));
//            if (videoView == null) {
//                videoView = new VideoView(MainActivity.this);
//            }
//            videoView.setVideoURI(Uri.parse("https://rmt.higozj.com/profile/upload/2024/05/15/20240515160348A016.mp4"));
            setTop =  dp2px(context, top * 1.0f);
            params.leftMargin = (int) (dp2px(context, left) * 1.0f);
            params.topMargin = (int) (dp2px(context, top) * 1.0f);

            View viewToChange = findViewById(R.id.webView);

            params.startToStart = viewToChange.getId();
            params.topToTop = viewToChange.getId();

//            videoView.setLayoutParams(params);
//            videoView.setBackgroundColor(Color.TRANSPARENT);
//            videoView.start();

            VideoViewPager viewPager = new VideoViewPager(context);
            List<MediaFragment> fragmentList = new ArrayList<>();
            fragmentList.add(new MediaFragment());
            fragmentList.add(new MediaFragment());
            fragmentList.add(new MediaFragment());
            FragmentViewPagerAdapter adapter = new FragmentViewPagerAdapter(MainActivity.this.getSupportFragmentManager(),fragmentList);
            viewPager.setAdapter(adapter);
            viewPager.setBackgroundColor(MainActivity.this.getColor(R.color.colorAccent));
            viewPager.freshLayoutParams(params);
//            viewPager.setLayoutParams(params);
            videoViewPagers.add(viewPager);

            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    rootView.addView(viewPager);
//                    videoView.invalidate();
//                    videoView.setBackgroundColor(Color.WHITE);
//                    videoView.setImageDrawable(context.getResources().getDrawable(R.drawable.shepherd));
                }
            });
        }
    }

    public static int dp2px(Context context, float dpVal) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpVal * scale + 0.5f);
    }
}
